<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ConfigController extends Controller
{
    //配置列表
    public function getIndex()
    {
        $data = DB::table('config')->get();
        //解析模板
        return view('Admin.config.index',['data'=>$data]);
    }

    //配置添加视图
    public function getAdd()
    {
        //解析模板
        return view('Admin.config.add');
    }

    //配置添加
    public function postInsert(Request $request)
    {
        $con = DB::table('config')->count();
        if($con >= 1){

            return back();

            return back()->with('error','只允许添加一条');

            return back();
        }
        $data = $request->except('_token');
        $data['logo'] = $this->upload($request);
        $res = DB::table('config')->insert($data);
        if($res){

          return redirect('admin/config/index');
          return redirect('/admin/config/index');
        }
    }

    //配置删除
    public function getDelete()
    {
        $del = DB::table('config')->delete();
        $data = DB::table('config')->get();
        return view('Admin.config.index',['data'=>$data]);
    }

    //配置修改的视图
    public function getEdit()
    {
        $data = DB::table('config')->first();
        return view('Admin.config.edit',['data'=>$data]);
    }

    //配置修改
    public function postUpdate(Request $request)
    {
        $data = $request->except('_token');
        if($request->hasFile('logo')){
           //调用方法进行头像的上传操作
           $data['logo'] = $this->upload($request);
        }
        $res = DB::table('config')->update($data);
        if($res){

            return redirect('Admin/config/index')->with('success','用户修改成功');

            return redirect('admin/config/index')->with('success','用户修改成功');

            return redirect('/admin/config/index')->with('success','用户修改成功');
        }else{
            return back()->with('error','用户修改失败');
        }
    }

    //图片上传
    public function upload($request)
    {
      if ($request->hasfile('logo')) {
          $aa = $request->file('logo')->getClientMimeType();
          $type = array('image/png','image/gif','image/jpeg');
          if(!in_array($aa, $type)){
              die('请选择正确的文件类型');
          }
          $name = md5(time()+rand(1,999999));
          $su = $request->file('logo')->getClientOriginalExtension();
          $request->file('logo')->move('./public/Uploads',$name.'.'.$su);
          return '/public/Uploads/'.$name.'.'.$su;
      }
    }
}
